import { getSelfMenus, getList } from '@/api/admin/permission'
import { constantRoutes } from '@/router/index'
import Layout from '@/Layout'

const state = {
    selfMenus: null,
    selfRouters: null,
    allButtomMenus: []
}

const mutations = {
    SET_SELFMENUS(state, selfMenus) {
        state.selfMenus = selfMenus
    },
    SET_SELFROUTERS(state, selfRouters) {
        state.selfRouters = constantRoutes.concat(selfRouters)
    },
    SET_ALLBUTTOMMENUS(state, allButtomMenus) {
        state.allButtomMenus = allButtomMenus
    },
    CLEAN_SELFMENUS(state) {
        state.selfMenus = null
        state.selfRouters = null
    }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
    return asyncRouterMap.filter((route) => {
        route.meta = {
            title: route.title
        }
        // Layout组件特殊处理
        if (route.component === 'Layout' || route.component === '') {
            route.component = Layout
        } else {
            route.component = loadView(route.component)
        }
        if (route.type === '1') {
            route.children = null
            
        } else if
            (route.children != null && route.children && route.children.length) {
            filterAsyncRouter(route.children)
        }
    })
}

export const loadView = (view) => { // 路由懒加载
    return (resolve) => require([`@/views/${view}`], resolve)
}

const actions = {
    // 获取当前用户菜单
    getSelfMenus({ commit }) {
        return new Promise((resolve, reject) => {
            getSelfMenus().then(response => {
                commit('SET_SELFMENUS', response.data)
                const selfRouters = JSON.parse(JSON.stringify(response.data))
                filterAsyncRouter(selfRouters)
                commit('SET_SELFROUTERS', selfRouters)
                actions.getAllButtomMenus(commit)
                resolve(response.data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 清空当前用户菜单
    cleanSelfMenus({ commit }) {
        return new Promise(resolve => {
            commit('CLEAN_SELFMENUS')
            resolve()
        })
    },

    // 获取所有按钮菜单
    getAllButtomMenus() {
        return new Promise(resolve => {
            getList({ type: '2' }).then(res => {
                console.log(res)
                // commit('SET_ALLBUTTOMMENUS', res.data)
            })
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations
}